import React, { useState } from 'react';
import NumberField from '../../../../../components/common/NumberField';
import StatefulCalculationCard from '../../../../../components/common/StatefulCalculationCard';
import ExportData from '../../../../../components/common/ExportCalculateData';
import type { ResultItem } from '../../../../../../shared/types';

// 隧道埋深计算类型定义
export interface TunnelDepthValues { 
    gamma: number,
    H: number,
    rockgrade: number,
}

// 隧道埋深计算结果类型定义
export interface TunnelDepthResult {
    depthtype: string;
    Hp: number;
    q: number;
}

// 隧道埋深计算初始值配置
const initialValues: TunnelDepthValues = {
    gamma: 20,
    H: 10,
    rockgrade: 5,
};

// 隧道洞口材料用量计算卡片组件配置
const tunnelDepthConfig = {
  key: 'TunnelDepth',
  label: '隧道埋深计算',
  formKey: 'tunnel-depth-calculation',
  initialValues: initialValues,
  calculationType: 'tunnel-depth-calculation',
  resultFormatter: (data: TunnelDepthResult) => [
    { key: 'depthtype', name: '埋深类型', value: data.depthtype, unit: '' },
    { key: 'Hp', name: '浅埋隧道分界深度', value: data.Hp, unit: 'm' },
    { key: 'q', name: '隧道垂直均布压力', value: data.q, unit: 'kPa' },
  ],
  renderFormFields: () => (
    <>
      <NumberField name="gamma" label="γ隧道上覆围岩重度" required step={0.001} tooltip="隧道上覆围岩重度，单位为kN/m3" />
      <NumberField name="H" label="隧道埋深" required step={0.001} tooltip="H隧道埋深，隧道顶至地面的距离，单位为m" />
      <NumberField name="rockgrade" label="围岩分级" required step={0.001} tooltip="围岩分级" />
    </>
  )
};

// 隧道埋深计算卡片组件实现
const TunnelDepthCard: React.FC = () => {
  const [lastResults, setLastResults] = useState<ResultItem[] | null>(null);
  
  return (
    <StatefulCalculationCard
      title={tunnelDepthConfig.label}
      formKey={tunnelDepthConfig.formKey}
      initialValues={tunnelDepthConfig.initialValues}
      renderFormFields={tunnelDepthConfig.renderFormFields}
      calculationType={tunnelDepthConfig.calculationType}
      resultFormatter={(data) => {
        const results = tunnelDepthConfig.resultFormatter(data);
        setLastResults(results);
        return results;
      }}
      columnCount={2} // 使用2列布局
      tableHeight={500} // 设置表格高度为500px
      exportComponent={(form) => (
        <ExportData
          siteName={tunnelDepthConfig.label}
          inputs={form.getFieldsValue()}
          results={lastResults ? Object.fromEntries(lastResults.map(r => [r.key, r.value])) : {}}
          calculationType={tunnelDepthConfig.calculationType}
        />
      )}
    />
  );
};

export default TunnelDepthCard;
